﻿var RegValidator = {};
RegValidator.RegTextEnum = {};
RegValidator.RegTextEnum.postCode = /^\d{6}$/;
RegValidator.RegTextEnum.email = /^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$/;
RegValidator.RegTextEnum.mobile = /^(13|15|18)[0-9]{9}$/;
RegValidator.RegTextEnum.tel = /^\d{3,4}-\d{7,9}$/;

Object.extend(RegValidator
    , {
        validate: function(reg, text) {
            return reg.test(text);
        },
        isEMail: function(text) {
            return this.validate(RegValidator.RegTextEnum.email, text);
        },
        isMobile: function(text) {
            return this.validate(RegValidator.RegTextEnum.mobile, text);
        },
        isTel: function(text) {
            return this.validate(RegValidator.RegTextEnum.tel, text);
        },
        isPostcode: function(text) {
            return this.validate(RegValidator.RegTextEnum.postCode, text);
        }
    }
    , false);

/*文本框验证*/
function ElementValidatorParams() {
    this.len = { "text": null, "errorMsg": null };
    this.reg = { "text": [], "errorMsg": [] }; //text 数组或正则
    this.error = { "id": "", "msg": "" };
    this.className = { error: "", def: "", focus: "" };
    this.onCallback = null;
}
ElementValidatorParams.prototype = {
    id: null,
    focus: null,
    defTips: null
}
function ElementValidator() {
    this.list = [];
}
ElementValidator.className = { error: "", def: "", focus: "" };
ElementValidator.format = function(rvp) {
    var attrList = ["reg", "len", "error", "className"], attrName = "";
    for (var i = 0, len = attrList.length; i < len; i++) {
        attrName = attrList[i];
        rvp["has" + attrName] = true;
        if (String.isNullOrEmpty(rvp[attrName])) { rvp[attrName] = {}; }
        if (attrName == "error") {
            if (String.isNullOrEmpty(rvp["error"]["id"])) { rvp["error"]["id"] = rvp["id"] + "_error_"; }
        } else {
            if (String.isNullOrEmpty(rvp[attrName]["text"])) {
                rvp[attrName]["text"] = null;
                rvp["has" + attrName] = false;
            }
        }
        if (String.isNullOrEmpty(rvp[attrName]["errorMsg"])) { rvp[attrName]["errorMsg"] = ""; }
//        if (attrName == "className") {
//            var classNameList = ["error", "def", "focus"], className = "";
//            for (var n = 0, nLen = classNameList.length; n < nLen; n++) {
//                className = classNameList[n];
//                if (String.isNullOrEmpty(rvp[attrName][className])) { rvp[attrName][className] = ""; }
//            }
//        }
    }
}
ElementValidator.showTips = function(rvp, errorMsg, className) {
    var defaultErrorMsg = String.isNullOrEmpty(errorMsg) ? rvp["error"]["msg"] : errorMsg;
    var errorId = rvp["error"]["id"];
    var errEle = jDoc(errorId);
    if (!errEle) {
        rvp["error"]["id"] = errorId;
        errEle = document.createElement("span");
        errEle.id = errorId;
        var ele = jDoc(rvp["id"]);
        ele.parentNode.insertBefore(errEle, ele.nextSibling);
    }
    errEle.innerHTML = defaultErrorMsg;
    if (typeof className === "string")
        errEle.className = className;
    errEle.style.display = "";
    return false;
}
ElementValidator.hideTips = function(rvp) {
    var errorEle = jDoc(rvp["error"]["id"]);
    if (errorEle) {
        errorEle.style.display = "none";
    }
}

ElementValidator.getBlurFn = function(elem, elemType) {
    var unknown = false, fn = function() { };
    switch (elemType) {
        case "textarea":
        case "input":
            fn = function() {
                var value = jDoc(this["id"]).value;
                if (this["haslen"]) {
                    if (this["len"]["text"].test(value.trim()) == false) {
                        return ElementValidator.showTips(this, this["len"]["errorMsg"], this["className"]["error"]);
                    }
                }
                if (String.isNullOrEmpty(value) == false && this["hasreg"]) {
                    var regList = this["reg"]["text"], errorList = this["reg"]["errorMsg"];
                    var flag = true;
                    if (regList.length == undefined) {
                        if (regList.test(value) == false) {
                            flag = false;
                        }
                    } else {
                        for (var i = 0, len = regList.length; i < len; i++) {
                            if (regList[i].test(value) == false) {
                                flag = false;
                            }
                        }
                    }
                    if (flag == false) {
                        return ElementValidator.showTips(this, errorList, this["className"]["error"]);
                    }
                }
                if (String.isNullOrEmpty(this["defTips"]) == false) {
                    ElementValidator.showTips(this, this["defTips"], this["className"]["def"]);
                } else {
                    ElementValidator.hideTips(this);
                }
                return true;
            }
            break
        case "checkbox":
        case "radio":
            fn = function() {
                var elems = document.getElementsByName(elem), num = 0;
                for (var i = 0, len = elems.length; i < len; i++) {
                    if (elems[i].checked) {
                        if (this["hasreg"] && elems[i].value.trim() != "") {
                            if (this["reg"]["text"].test(elems[i].value)) {
                                return ElementValidator.showTips(this, this["reg"]["errorMsg"], this["className"]["error"]); ;
                            }
                        }
                        num++;
                    }
                }
                if (this["haslen"]) {//maybe checkbox
                    if (this["len"]["text"].test(num) == false) {
                        return ElementValidator.showTips(this, this["len"]["errorMsg"], this["className"]["error"]);
                    }
                } else {
                    if (num == 0) {
                        ElementValidator.showTips(this, this["error"]["msg"], this["className"]["error"]);
                        return false;
                    }
                }
                ElementValidator.hideTips(this);
                return true;
            }
            break;
        case "select":
            fn = function() {
                var elem = jDoc(this["id"]), flag = true;
                if (elem.selectedIndex < 0) {
                    flag = false;
                } else {
                    if (this["len"]["text"].test(elem.selectedIndex)) {
                        flag = ElementValidator.showTips(this, this["len"]["errorMsg"], this["className"]["error"]);
                    }
                }
                if (flag) {
                    ElementValidator.hideTips(this);
                    return true;
                } else {
                    return false;
                }
            }
            break;
        default: unknown = true; break;
    }
    if (unknown) {
        alert("该元素类型不能使用该方法" + rvp["id"]);
        return fn;
    }

    return fn;
}
ElementValidator.prototype = {
    init: function(rvp) {
        ElementValidator.format(rvp);
        Object.extend(rvp["className"], ElementValidator.className, false);
        rvp["onblur"] = function() { return true; };
        if (String.isNullOrEmpty(rvp["defTips"]) == false) {
            ElementValidator.showTips(rvp, rvp["defTips"], rvp["className"]["def"]);
        }
        if (String.isNullOrEmpty(rvp["focus"]) == false) {
            jDoc.addEventHandler(jDoc(rvp["id"]), "focus", function() { ElementValidator.showTips(this, this.focus, this["className"]["focus"]); } .bind(rvp));
        }
    },
    addText: function(rvp) {
        var ele = jDoc(rvp.id)
        if (ele) {
            this.init(rvp);
            if (rvp["haslen"] || rvp["hasreg"]) {
                rvp["onblur"] = ElementValidator.getBlurFn(ele, "input");
                jDoc.addEventHandler(ele, "blur", rvp["onblur"].bind(rvp));
            }
            this.list.push(rvp);
        }
    },
    addInputElem: function(rvp, type) {
        this.init(rvp);
        rvp["onblur"] = ElementValidator.getBlurFn(rvp.id, type);
        var elems = document.getElementsByName(rvp.id);
        for (var i = 0, len = elems.length; i < len; i++) {
            jDoc.addEventHandler(elems[i], "click", function() { rvp["onblur"].bind(rvp)(); });
        }
        this.list.push(rvp);
    },
    addRadio: function(rvp) {
        this.addInputElem(rvp, "radio");
    },
    addCheckbox: function(rvp) {
        this.addInputElem(rvp, "checkbox");
    },
    addSelect: function(rvp) {
        var ele = jDoc(rvp.id)
        if (ele) {
            this.init(rvp);
            rvp["onblur"] = ElementValidator.getBlurFn(rvp.id, "select");
            jDoc.addEventHandler(ele, "change", rvp["onblur"].bind(rvp));
            this.list.push(rvp);
        }
    },
    validate: function() {
        var num = 0;
        for (var i = 0, len = this.list.length; i < len; i++) {
            if (this.list[i]["onblur"]() == false) {
                num++;
            }
        }
        return num > 0 ? false : true;
    }
}